﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Diagnostics;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace SCCL2010
{
    public class UsersAndGroups
    {
        public static SPGroup GetGroup(SPWeb oWeb, SPListItem item, string displayName)
        {
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                //get field and cast to User Field type   
                var field = item.Fields.GetField(displayName) as SPFieldUser;

                if (null == field)
                {
                    throw new ApplicationException("This field is not a User!");
                }

                var fieldValue = field.GetFieldValue(item[field.Id].ToString()) as SPFieldUserValue;

                if (null == fieldValue)
                {
                    return null;
                }
                if (fieldValue.User == null)
                {
                    string cGroupName = item[field.Id].ToString();
                    cGroupName = cGroupName.Substring(cGroupName.IndexOf('#') + 1);
                    return UsersAndGroups.GetGroup(oWeb, cGroupName);
                }

                //return fieldValue.User;
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "UsersAndGroups.GetGroup", ex);
            }
            return null;
        }


        /// <summary>
        /// Get an SPUser object from a list item.
        /// </summary>
        /// <param name="oWeb">SharePoint Web Reference</param>
        /// <param name="item">SharePoint List Item to look in.</param>
        /// <param name="displayName">SharePoint Field Name to get user from.</param>
        /// <returns>returns SPUSer object representing user value in field or null.</returns>
        public static SPUser GetUser(SPWeb oWeb, SPListItem item, string displayName)
        {
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                //get field and cast to User Field type   
                var field = item.Fields.GetField(displayName) as SPFieldUser;

                if (null == field)
                {
                    throw new ApplicationException("This field is not a User!");
                }

                var fieldValue = field.GetFieldValue(item[field.Id].ToString()) as SPFieldUserValue;

                if (null == fieldValue)
                {
                    return null;
                }

                return fieldValue.User;
            }
            catch (Exception ex)
            {
                Trace.Write(String.Format("GetUser - {0} {1}", displayName, ex.Message));
                ErrorHandling.HandleError("UsersAndGroups.GetUser", "", ex);
            }
            return null;
        }

        /// <summary>
        /// Get an SPUser object from a list item.
        /// </summary>
        /// <param name="item">SharePoint List Item to look in.</param>
        /// <param name="displayName">SharePoint Field Name to get user from.</param>
        /// <returns>returns SPUSer object representing user value in field or null.</returns>
        public static SPUser GetUser(SPListItem item, string displayName)
        {
            try
            {
                if (item[displayName] != null)
                {
                    SPFieldUserValue fuv = new SPFieldUserValue(item.ParentList.ParentWeb, item[displayName].ToString());
                    if (fuv != null)
                    {
                        return fuv.User;
                    }
                    ////get field and cast to User Field type   
                    //var field = item.Fields.GetField(displayName) as SPFieldUser;

                    //if (null == field)
                    //{
                    //    throw new ApplicationException("This field is not a User!");
                    //}

                    //var fieldValue = field.GetFieldValue(item[field.Id].ToString()) as SPFieldUserValue;

                    //if (null == fieldValue)
                    //{
                    //    return null;
                    //}

                    //return fieldValue.User;
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(item.ParentList.ParentWeb, "UsersAndGroups.GetUser", ex);
            }
            return null;
        }


        /// <summary>
        /// returns a list item reference to the user information in the current site collection.
        /// </summary>
        /// <param name="user">SPUser Value</param>
        /// <returns>returns a list item reference to the user information in the current site collection.</returns>
        public static SPListItem GetUserInfo(SPUser user)
        {
            //guard   
            if (null == user)
            {
                return null;
            }
            return user.ParentWeb.SiteUserInfoList.GetItemById(user.ID);
        }

        /// <summary>
        /// returns an SPFieldUserValue from a field in a list item.
        /// </summary>
        /// <param name="oWeb">SharePoint Web to Look in.</param>
        /// <param name="item">SharePoint List Item to Look in.</param>
        /// <param name="cFieldName">Field Name to look in.</param>
        /// <returns>returns a list item reference to the user information in the current site collection.</returns>
        public static SPFieldUserValue GetUserValue(SPWeb oWeb, SPListItem item, String cFieldName)
        {

            try
            {
                oWeb.AllowUnsafeUpdates = true;
                SPFieldUserValue userValue = new SPFieldUserValue(oWeb, item[cFieldName].ToString());
                return userValue;
            }
            catch (Exception ex)
            {
                Trace.Write("GetUserValue " + ex.Message);
                ErrorHandling.HandleError("UsersAndGroups.GetUserValue", "", ex);


            }
            return null;
        }


        /// <summary>
        /// returns the Display Name for a User.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="item"></param>
        /// <param name="cFieldName"></param>
        /// <returns></returns>
        public static string GetUserName(SPWeb oWeb, SPListItem item, String cFieldName)
        {
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                SPFieldUserValue userValue = new SPFieldUserValue(oWeb, item[cFieldName].ToString());
                return userValue.User.Name;
            }
            catch (Exception ex)
            {
                Trace.Write("GetUserName " + ex.Message);
                ErrorHandling.HandleError("UsersAndGroups.GetUserName", "", ex);


            }
            return "";
        }

        /// <summary>
        /// Sets the security of a list item.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="newItem"></param>
        /// <param name="list"></param>
        public static void SetItemSecurity(SPWeb oWeb, SPListItem newItem, SPList list)
        {
            oWeb.AllowUnsafeUpdates = true;
            newItem.BreakRoleInheritance(false);

            SPRoleDefinitionCollection roleDefinitions = list.ParentWeb.RoleDefinitions;
            SPRoleAssignmentCollection roleAssignments = newItem.RoleAssignments;

            SPUserCollection users = list.ParentWeb.AllUsers;

            try
            {
                //String cContractManager;
                ////SPUser userToAdd = list.ParentWeb.EnsureUser(cUser);
                ////SPRoleAssignment roleAssignment = new SPRoleAssignment(userToAdd);
                //SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
                //roleDefBindings.Add(roleDefinitions["Contribute"]);
                //roleAssignments.Add(roleAssignment);
            }
            catch (Exception ex)
            {
                Trace.Write("SetItemSecurity " + ex.Message);
                ErrorHandling.HandleError("UsersAndGroups.SetItemSecurity", "", ex);


            }
        }

        /// <summary>
        /// Returns the SPUser item of the user to be assigned the task.
        /// </summary>
        /// <param name="wfProperties"></param>
        /// <param name="cFieldName"></param>
        /// <returns></returns>
        public static SPUser GetTaskUser(SPWorkflowActivationProperties wfProperties, String cFieldName)
        {
            try
            {
                SPList oDelegationList = wfProperties.Web.Lists["Contract Delegation"];
                SPQuery oQuery = new SPQuery();
                SPUser oContractUser = UsersAndGroups.GetUser(wfProperties.Web, wfProperties.Item, cFieldName);
                Int32 UserID = oContractUser.ID;

                string cToday = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);

                String cQuery = String.Format("<Where><And><And><Eq><FieldRef Name=\"DelegatedFrom\" LookupId='TRUE' /><Value Type=\"User\">{0}</Value></Eq><Leq><FieldRef Name=\"DelegationStartDate\" /><Value Type=\"DateTime\">{1}</Value></Leq></And><Geq><FieldRef Name=\"DelegationEndDate\" /><Value Type=\"DateTime\">{1}</Value></Geq></And></Where>", UserID, cToday);

                //cQuery = "<Where><Eq><FieldRef Name=\"DelegatedFrom\" /><Value Type=\"Integer\">" + UserID + "</Value></Eq>";
                oQuery.Query = cQuery;

                SPListItemCollection oItems = oDelegationList.GetItems(oQuery);

                foreach (SPListItem item in oItems)
                {
                    return UsersAndGroups.GetUser(wfProperties.Web, item, "Delegate Work To");
                }

                return oContractUser;
            }
            catch (Exception ex)
            {
                Trace.Write("GetDelegateUser " + ex.Message);
                ErrorHandling.HandleError("UsersAndGroups.GetTaskUser", "", ex);


            }

            return null;
        }

        /// <summary>
        /// Returns the SPUser item of the user to be assigned the task.
        /// </summary>
        /// <param name="wfProperties"></param>
        /// <param name="oCurrentUser"></param>
        /// <returns></returns>
        public static SPUser GetTaskUser(SPWorkflowActivationProperties wfProperties, SPUser oCurrentUser)
        {
            try
            {
                SPList oDelegationList = wfProperties.Web.Lists["Contract Delegation"];
                SPQuery oQuery = new SPQuery();

                Int32 UserID = oCurrentUser.ID;

                string cToday = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);

                String cQuery = String.Format("<Where><And><And><Eq><FieldRef Name=\"DelegatedFrom\" LookupId='TRUE' /><Value Type=\"User\">{0}</Value></Eq><Leq><FieldRef Name=\"DelegationStartDate\" /><Value Type=\"DateTime\">{1}</Value></Leq></And><Geq><FieldRef Name=\"DelegationEndDate\" /><Value Type=\"DateTime\">{1}</Value></Geq></And></Where>", UserID, cToday);

                //cQuery = "<Where><Eq><FieldRef Name=\"DelegatedFrom\" /><Value Type=\"Integer\">" + UserID + "</Value></Eq>";
                oQuery.Query = cQuery;

                SPListItemCollection oItems = oDelegationList.GetItems(oQuery);

                foreach (SPListItem item in oItems)
                {
                    return UsersAndGroups.GetUser(wfProperties.Web, item, "Delegate Work To");
                }

                return oCurrentUser;
            }
            catch (Exception ex)
            {
                Trace.Write("GetDelegateUser " + ex.Message);
                ErrorHandling.HandleError("UsersAndGroups.GetTaskUser", "", ex);


            }

            return null;
        }

        /// <summary>
        /// Gets the Profile Property based on the specified PropertyName and the UserID.
        /// </summary>
        /// <param name="iUserID"></param>
        /// <param name="context"></param>
        /// <param name="cPropertyName"></param>
        /// <returns>returns a string value representing the UserProfileProperty based on the PropertyName and UserID.</returns>
        

        private static void HandleError(string cLocation, Exception ex)
        {

        }

        /// <summary>
        /// Checks whether the LoginName belongs to the valid user or not and returns the SPUser.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="LoginName"></param>
        /// <returns>return a SPUser object representing the LoginName is a Valid user.</returns>
        public static SPUser EnsureUser(SPWeb oWeb, String LoginName)
        {
            string cWebURL = oWeb.Url;
            SPUser oUser = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                try
                {
                    using (SPSite oSite = new SPSite(cWebURL))
                    {
                        using (SPWeb oRootWeb = oSite.RootWeb)
                        {
                            try
                            {
                                oRootWeb.AllowUnsafeUpdates = true;
                                oUser = oRootWeb.EnsureUser(LoginName);
                                oRootWeb.AllowUnsafeUpdates = false;
                            }
                            catch
                            {
                                try
                                {
                                    oRootWeb.AllowUnsafeUpdates = true;
                                    oUser = oRootWeb.SiteUsers[LoginName];
                                }
                                catch
                                {

                                    try
                                    {
                                        oRootWeb.AllowUnsafeUpdates = true;
                                        oUser = oRootWeb.SiteUsers["US\\" + LoginName];
                                    }
                                    catch (Exception Ex)
                                    {
                                        HandleError("Unable to Validate User: " + LoginName, Ex);
                                        oUser = null;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    HandleError("Unable to Validate User: " + LoginName, ex);
                }
            });
            return oUser;
        }

        /// <summary>
        /// Adds RoleAssignments to the Group.
        /// </summary>
        /// <param name="cSiteURL"></param>
        /// <param name="cWebRelativeUrl"></param>
        /// <param name="cListName"></param>
        /// <param name="itemID"></param>
        /// <param name="cPermission"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns a boolean value representing the GroupName is added to the SiteGroups.</returns>
        public static bool AddGroupPermission(String cSiteURL, String cWebRelativeUrl, String cListName, Int32 itemID, String cPermission, String cGroupName)
        {
            try
            {
                if (itemID == 0) return false;
                if (cGroupName.Trim() == "") return false;
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    try
                    {
                        using (SPSite oSite = new SPSite(cSiteURL))
                        {
                            try
                            {
                                using (SPWeb oWeb = oSite.OpenWeb(cWebRelativeUrl))
                                {
                                    oWeb.AllowUnsafeUpdates = true;
                                    SPGroup oGroup;
                                    if (IsSiteGroup(oWeb, cGroupName))
                                        oGroup = oWeb.SiteGroups[cGroupName];
                                    else
                                        oGroup = oWeb.Groups[cGroupName];
                                    if (oGroup != null)
                                    {
                                        oWeb.AllowUnsafeUpdates = true;
                                        SPList oList = oWeb.Lists[cListName];
                                        SPListItem oItem = oList.GetItemById(itemID);
                                        if (!oItem.HasUniqueRoleAssignments)
                                        {
                                            oItem.BreakRoleInheritance(false);
                                        }
                                        SPRoleDefinitionCollection roleDefinitions = oWeb.RoleDefinitions;
                                        SPRoleAssignmentCollection roleAssignments = oItem.RoleAssignments;
                                        SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);
                                        SPRoleDefinitionBindingCollection roleDefBindings = oRoleAssignment.RoleDefinitionBindings;
                                        roleDefBindings.Add(roleDefinitions[cPermission]);
                                        oWeb.AllowUnsafeUpdates = true;
                                        oSite.AllowUnsafeUpdates = true;
                                        roleAssignments.Add(oRoleAssignment);
                                        oWeb.AllowUnsafeUpdates = false;
                                        oSite.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ErrorHandling.HandleError(oSite.RootWeb, "AddGroupPermission - Inside Using", ex);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleError("AddGroupPermssion - Inside " + cGroupName, ex);
                    }
                });
            }
            catch (Exception ex)
            {
                HandleError("AddGroupPermssion " + cGroupName, ex);
            }
            return false;
        }

        /// <summary>
        /// Adds new RoleAssignment to the ListItem of ListName with the specified Permission.
        /// </summary>
        /// <param name="cSiteURL"></param>
        /// <param name="cWebRelativeUrl"></param>
        /// <param name="cListName"></param>
        /// <param name="itemID"></param>
        /// <param name="cPermission"></param>
        /// <param name="cUserName"></param>
        /// <returns>returns a boolean value representing RoleAssignment is added to the ListItem of ListName whose ListItemID is ItemID.</returns>
        public static bool AddUserPermission(String cSiteURL, String cWebRelativeUrl, String cListName, Int32 itemID, String cPermission, String cUserName)
        {
            try
            {
                if (itemID == 0) return false;

                if (cUserName.Trim() == "") return false;

                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    try
                    {
                        using (SPSite oSite = new SPSite(cSiteURL))
                        {
                            try
                            {
                                using (SPWeb oWeb = oSite.OpenWeb(cWebRelativeUrl))
                                {
                                    oWeb.AllowUnsafeUpdates = true;
                                    SPUser oUser = EnsureUser(oWeb, cUserName);
                                    if (oUser != null)
                                    {
                                        oWeb.AllowUnsafeUpdates = true;
                                        oSite.AllowUnsafeUpdates = true;
                                        SPList oList = oWeb.Lists[cListName];
                                        SPListItem oItem = oList.GetItemById(itemID);
                                        if (!oItem.HasUniqueRoleAssignments)
                                            oItem.BreakRoleInheritance(false);
                                        SPRoleDefinitionCollection roleDefinitions = oWeb.RoleDefinitions;
                                        SPRoleAssignmentCollection roleAssignments = oItem.RoleAssignments;
                                        SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oUser);
                                        SPRoleDefinitionBindingCollection roleDefBindings = oRoleAssignment.RoleDefinitionBindings;
                                        roleDefBindings.Add(roleDefinitions[cPermission]);
                                        oWeb.AllowUnsafeUpdates = true;
                                        oSite.AllowUnsafeUpdates = true;
                                        roleAssignments.Add(oRoleAssignment);
                                        oSite.AllowUnsafeUpdates = false;
                                        oWeb.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                HandleError("AddUserPermission - Inside Using", ex);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleError("AddUserPermssion - Inside " + cUserName, ex);
                    }
                });
            }
            catch (Exception ex)
            {
                HandleError("AddUserPermssion - " + cUserName, ex);
            }
            return false;
        }

        /// <summary>
        /// Checks whether or not if the RoleDefinitions has the RoleName.
        /// </summary>
        /// <param name="cSiteURL"></param>
        /// <param name="cWebRelativeUrl"></param>
        /// <param name="cRoleName"></param>
        /// <returns>returns a boolean value representing whether or not Role exists.</returns>
        public static bool HasRole(string cSiteURL, string cWebRelativeUrl, string cRoleName)
        {
            bool retVal = false;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                try
                {
                    using (SPSite oSite = new SPSite(cSiteURL))
                    {
                        try
                        {
                            using (SPWeb oWeb = oSite.OpenWeb(cWebRelativeUrl))
                            {
                                foreach (SPRoleDefinition role in oWeb.RoleDefinitions)
                                {
                                    if (role.Name == cRoleName)
                                        retVal = true;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleError("HasRole - Inside Using", ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    HandleError("HasRole - Inside ", ex);
                }
            });
            return retVal;
        }

        /// <summary>
        /// Adds new Role to the current webs RoleDefinitions.
        /// </summary>
        /// <param name="cSiteURL"></param>
        /// <param name="cWebRelativeUrl"></param>
        /// <param name="cRoleName"></param>
        /// <param name="permissions"></param>
        public static void AddRole(string cSiteURL, string cWebRelativeUrl, string cRoleName, SPBasePermissions permissions)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                try
                {
                    using (SPSite oSite = new SPSite(cSiteURL))
                    {
                        try
                        {
                            using (SPWeb oWeb = oSite.OpenWeb(cWebRelativeUrl))
                            {
                                SPRoleDefinition def = new SPRoleDefinition { BasePermissions = permissions, Name = cRoleName };
                                oWeb.FirstUniqueRoleDefinitionWeb.RoleDefinitions.Add(def);
                                oWeb.FirstUniqueRoleDefinitionWeb.Update();
                                oWeb.FirstUniqueRoleDefinitionWeb.Dispose();
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleError("HasRole - Inside Using", ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    HandleError("HasRole - Inside ", ex);
                }
            });



        }
        /// <summary>
        /// Clears all the RoleAssignments of the ListItem based on the ListName and the ItemID.
        /// </summary>
        /// <param name="cSiteURL"></param>
        /// <param name="cWebRelativeUrl"></param>
        /// <param name="cListName"></param>
        /// <param name="itemID"></param>
        /// <returns>returns a boolean value representing whether or not the ListItem has RoleAssignments assigned to it.</returns>
        public static bool ClearPermissions(String cSiteURL, String cWebRelativeUrl, String cListName, Int32 itemID)
        {
            try
            {
                if (itemID == 0) return false;
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    try
                    {
                        using (SPSite oSite = new SPSite(cSiteURL))
                        {
                            try
                            {
                                using (SPWeb oWeb = oSite.OpenWeb(cWebRelativeUrl))
                                {
                                    oWeb.AllowUnsafeUpdates = true;

                                    oWeb.AllowUnsafeUpdates = true;
                                    oSite.AllowUnsafeUpdates = true;
                                    SPList oList = oWeb.Lists[cListName];
                                    SPListItem oItem = oList.GetItemById(itemID);

                                    if (!oItem.HasUniqueRoleAssignments)
                                    {
                                        oItem.BreakRoleInheritance(false);
                                        return;
                                    }
                                    else
                                    {
                                        oWeb.AllowUnsafeUpdates = true;
                                        oSite.AllowUnsafeUpdates = true;

                                        while (oItem.RoleAssignments.Count > 0)
                                        {
                                            oItem.RoleAssignments.Remove(0);
                                        }
                                        oSite.AllowUnsafeUpdates = false;
                                        oWeb.AllowUnsafeUpdates = false;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                HandleError("AddUserPermission - Inside Using", ex);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleError("AddUserPermssion - Inside ", ex);
                    }
                });
            }
            catch (Exception ex)
            {
                HandleError("AddUserPermssion - ", ex);
            }
            return false;
        }

        /// <summary>
        /// Gets the SPGroup(SiteGroup/Group) based on the GroupName
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns a SPGroup object representing the SPGroup(SiteGroup/Group) for the GroupName.</returns>
        public static SPGroup GetGroup(SPWeb oWeb, string cGroupName)
        {
            if (IsSiteGroup(oWeb, cGroupName))
            {
                foreach (SPGroup grp in oWeb.SiteGroups)
                {
                    if (cGroupName == grp.Name)
                    {
                        return grp;
                    }
                }


            }
            if (IsGroup(oWeb, cGroupName))
            {
                foreach (SPGroup grp in oWeb.Groups)
                {
                    if (cGroupName == grp.Name)
                    {
                        return grp;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// Gets the Email Address of the GroupName.
        /// </summary>
        /// <param name="oCurrentWeb"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns a string value representing the Email Address of the Supplied GroupName.</returns>
        public static string GetGroupEmailAddresses(SPWeb oCurrentWeb, string cGroupName)
        {
            string cEmailAddresses = "";

            string cSiteUrl = oCurrentWeb.Site.Url;
            string cWebUrl = oCurrentWeb.ServerRelativeUrl;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite oSite = new SPSite(cSiteUrl))
                {
                    SPWeb oWeb = oSite.OpenWeb(cWebUrl);


                    SPGroup oGroup = GetGroup(oWeb, cGroupName);
                    foreach (SPUser user in oGroup.Users)
                    {
                        if (user.Email != "")
                            cEmailAddresses += user.Email + ";";
                    }
                }

            });
            return cEmailAddresses;
        }

        /// <summary>
        /// Checks whether or not GroupName is a Group or SiteGroup.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns a boolean value representing whether or not GroupName is a Group or SiteGroup.</returns>
        public static bool HasGroup(SPWeb oWeb, string cGroupName)
        {
            if (IsGroup(oWeb, cGroupName) || IsSiteGroup(oWeb, cGroupName))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Checks whether or not the GroupName is a SiteGroup of SiteGroups.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns a boolean value representing the GroupName is a SiteGroup or not.</returns>
        public static bool IsSiteGroup(SPWeb oWeb, String cGroupName)
        {
            try
            {

                oWeb.AllowUnsafeUpdates = true;
                try
                {
                    foreach (SPGroup grp in oWeb.SiteGroups)
                    {
                        if (grp.Name == cGroupName)
                            return true;
                    }
                }
                catch (Exception ex)
                {
                    HandleError("IsSiteGroup - Inside Using", ex);
                }

            }
            catch (Exception ex)
            {
                HandleError("IsSiteGroup", ex);
            }
            return false;
        }

        /// <summary>
        /// Checks if the supplied GroupName exists in the Groups(Cross-Site groups for the site).
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cGroupName"></param>
        /// <returns>returns the boolean value representing whether or not group exists.</returns>
        public static bool IsGroup(SPWeb oWeb, String cGroupName)
        {
            try
            {
                oWeb.AllowUnsafeUpdates = true;
                try
                {
                    foreach (SPGroup grp in oWeb.Groups)
                    {
                        if (grp.Name == cGroupName)
                            return true;
                    }
                }
                catch (Exception ex)
                {
                    HandleError("IsGroup - Inside Using", ex);
                }

            }
            catch (Exception ex)
            {
                HandleError("IsGroup", ex);
            }
            return false;
        }

        /// <summary>
        /// Adds a group to the SiteGroups(Cross-Site groups of the site collection) of the particular web.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cGroupName"></param>
        /// <param name="cDescription"></param>
        /// <param name="cRoleAssignment"></param>
        public static void AddGroup(SPWeb oWeb, string cGroupName, string cDescription, string cRoleAssignment)
        {
            try
            {
                oWeb.SiteGroups.Add(cGroupName, oWeb.CurrentUser, oWeb.CurrentUser, cDescription);
                oWeb.AssociatedGroups.Add(oWeb.SiteGroups[cGroupName]);
                oWeb.Update();
                SPRoleAssignment asgn = new SPRoleAssignment(oWeb.SiteGroups[cGroupName]);
                SPRoleDefinition con = oWeb.RoleDefinitions["Contribute"];
                asgn.RoleDefinitionBindings.Add(con);
                oWeb.SiteGroups[cGroupName].Update();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "AddGroup", ex);

            }
        }

        /// <summary>
        /// Checks whether or not the user exists in the SPGroup.
        /// </summary>
        /// <param name="oGroup"></param>
        /// <param name="cLoginName"></param>
        /// <param name="cEmail"></param>
        /// <param name="cName"></param>
        /// <param name="bAddIfNotMember"></param>
        /// <returns>returns boolean value representing whether the user exists in the group.</returns>
        public static bool HasUser(SPGroup oGroup, string cLoginName, string cEmail, string cName, bool bAddIfNotMember)
        {
            try
            {
                foreach (SPUser usr in oGroup.Users)
                {
                    if (usr.LoginName.ToUpper() == cLoginName.ToUpper())
                    {
                        return true;
                    }
                }
                oGroup.AddUser(cLoginName, cEmail, cName, "Automatically added by code.");
                return true;
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oGroup.ParentWeb, "HasUser = " + cLoginName, ex);
            }
            return false;
        }

        /// <summary>
        /// Creates PickerEntity object and updates the PeopleEditor with the supplied ListItem and FieldName.
        /// </summary>
        /// <param name="peFieldName"></param>
        /// <param name="oItem"></param>
        /// <param name="cFieldName"></param>
        private static void SetPeopleEditor(PeopleEditor peFieldName, SPListItem oItem, string cFieldName)
        {
            try
            {
                if (oItem[cFieldName] != null)
                {
                    string cFieldValue = oItem[cFieldName].ToString();
                    cFieldValue = cFieldValue.Substring(cFieldValue.IndexOf('#') + 1);
                    System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
                    PickerEntity entity = new PickerEntity();
                    entity.Key = cFieldValue;
                    entity = peFieldName.ValidateEntity(entity);
                    entityArrayList.Add(entity);
                    peFieldName.UpdateEntities(entityArrayList);
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oItem.Web, "UsersAndGroups.SetPeopleEditor", ex);
            }
        }

        /// <summary>
        /// Gets the SPFieldUserValueCollection for the specified peopleEditor
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="peField"></param>
        /// <returns>returns the SPFieldUserValueCollection object for the specified PeopleEditor.</returns>
        private static SPFieldUserValueCollection GetPeopleEditor(SPWeb oWeb, PeopleEditor peField)
        {
            try
            {
                string submitter = peField.CommaSeparatedAccounts;
                char[] splitter = { ',' };
                string[] splitPPData = submitter.Split(splitter);
                SPFieldUserValueCollection values = new SPFieldUserValueCollection();
                for (int i = 0; i < splitPPData.Length; i++)
                {
                    string loginName = splitPPData[i];
                    if (!string.IsNullOrEmpty(loginName))
                    {
                        SPUser user = oWeb.SiteUsers[loginName];
                        SPFieldUserValue fuv = new SPFieldUserValue(oWeb, user.ID, user.LoginName);
                        values.Add(fuv);
                    }
                }
                return values;
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "UsersAndGroups.GetPeopleEditor", ex);
            }
            return null;
        }


    }
}
